/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler;

import java.util.LinkedList;

import jp.aist.gtrc.plus.reserve.ReserveId;
import jp.aist.gtrc.plus.scheduler.sys.SchedulerException;
import jp.aist.gtrc.plus.scheduler.util.TimeUtil;

public class ScheduleStarter {

	private long startPeriod; // [msec]
	private final LinkedList<ScheduleOrder> orders;
	private boolean toBeQuit;
	private final ScheduleOrder defaultOrder;

	public static final int DEFAULT_SCHEDULING_PERIOD = 30;		// [sec]
	private static final int MINIMUM_SCHEDULING_PERIOD = 10;	// [sec]

	public ScheduleStarter() throws SchedulerException {

		this.orders = new LinkedList<ScheduleOrder>();
		setStartPeriod(DEFAULT_SCHEDULING_PERIOD);
		this.toBeQuit = false;
		this.defaultOrder = new ScheduleOrder();

	}

	protected final void setStartPeriod(int timeout){

		if (timeout >= MINIMUM_SCHEDULING_PERIOD)
			startPeriod = TimeUtil.secToMilli(timeout);
		else
			startPeriod = TimeUtil.secToMilli(MINIMUM_SCHEDULING_PERIOD);

	}

	public synchronized void runSchedule(ScheduleOrder order){

		if (order.toBeQuit()) {
			toBeQuit = true;
			orders.addFirst(order);
		} else {
			if (orders.size() > 0) {
				ScheduleOrder last = orders.getLast();
				if (order.equals(last)) {
					// Duplicate orders are ignored
					return;
				}
			}
			orders.addLast(order);
		}

		notify();	// wake up waitOrder()

	}

	public synchronized ScheduleOrder waitOrder() throws SchedulerException {

		if (orders.size() > 0) {
			return orders.removeFirst();
		}

		boolean wakeupOK;
		do {
			wakeupOK = true;
			try {
				wait(startPeriod);
			} catch (Exception e) {
				wakeupOK = false;
			}
		} while (wakeupOK == false);

		if (orders.size() == 0) {
			// wait() was timeout
			return makePeriodicalScheduleOrder();
		} else {
			// runSchedule() was called by someone
			return orders.removeFirst();
		}

	}

	public synchronized boolean toBeQuit() {

		return toBeQuit;

	}

	protected ScheduleOrder makePeriodicalScheduleOrder() throws SchedulerException {

		return defaultOrder;

	}

	public void runSchedule(ReserveId reserveId) throws SchedulerException {

		runSchedule(defaultOrder);

	}

}
